package com.swdlfing.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swdlfing.shortlink.admin.common.biz.user.UserContext;
import com.swdlfing.shortlink.admin.common.convention.exception.ClientException;
import com.swdlfing.shortlink.admin.common.convention.exception.ServiceException;
import com.swdlfing.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.swdlfing.shortlink.admin.dao.entity.UserDO;
import com.swdlfing.shortlink.admin.dao.mapper.UserMapper;
import com.swdlfing.shortlink.admin.dto.req.UserLoginReqDTO;
import com.swdlfing.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.swdlfing.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.swdlfing.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.swdlfing.shortlink.admin.dto.resp.UserRespDTO;
import com.swdlfing.shortlink.admin.service.GroupService;
import com.swdlfing.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.swdlfing.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.swdlfing.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.swdlfing.shortlink.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;


    /**
     * 根据用户名查询用户已脱敏信息
     *
     * @param username 用户名
     * @return
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ServiceException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtil.copyProperties(userDO, result);
        return result;
    }

    /**
     * 查询是否可以创建此名称的用户
     *
     * @param username 用户名
     * @return
     */
    @Override
    public Boolean availableUsername(String username) {
        //如果布隆过滤器存在username，说明不可以用
        // todo  存在误判问题,思考误判的过程
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 注册用户
     *
     * @param requestParam 注册用户请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserRegisterReqDTO requestParam) {
        if (!availableUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        // todo  回头好好看看redissonClient是如何实现的
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        if (!lock.tryLock()) {
            throw new ClientException(USER_NAME_EXIST);
        }
        try {
            int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if (inserted < 1) {
                // 这里是插入失败，并不是唯一索引导致的
                throw new ClientException(USER_SAVE_ERROR);
            }
            // 用户注册时添加默认分组
            groupService.saveGroup(requestParam.getUsername(), "默认分组");
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
        } catch (DuplicateKeyException ex) {
            // 此处拦截的是主键冲突，插入数据失败异常
            // 两个地方判断的原因不同，返回的错误信息也是不同的
            throw new ClientException(USER_EXIST);
        } finally {
            lock.unlock();
        }
    }


    /**
     * 根据用户名修改用户
     *
     * @param requestParam 修改用户请求参数
     */
    @Override
    public void update(UserUpdateReqDTO requestParam) {
        // 判断是否为当前用户
        if (!Objects.equals(requestParam.getUsername(), UserContext.getUsername())) {
            throw new ClientException("当前登录用户修改请求异常");
        }
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        // todo 没有修改redis中保存的用户临时数据
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    /**
     * 用户登录
     *
     * @param requestParam 用户登录请求参数
     * @return
     */
    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException("用户不存在或者用户密码错误");
        }
        /* 先看看缓存中有没有，如果有的话直接使用token登录
         如果没有，那么建立新的缓存*/
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    // 如果流中没有元素，则表示用户登录错误，抛出 ClientException 异常。
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * value：
         *  hashKey：token标识(其实就是上面的value)
         *  Val：JSON 字符串（用户信息）
         */
        // 也可以使用别的实现方式，比如使用string类型数据存储
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.HOURS);
        // 返回token
        return new UserLoginRespDTO(uuid);
    }

    /**
     * 检查用户是否登录
     *
     * @param username 用户名
     * @param token    用户登录 Token
     * @return
     */
    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    /**
     * 用户退出登录
     *
     * @param username 用户名
     * @param token    用户登录 Token
     */
    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}
